package com.gdwp;


import com.alibaba.excel.EasyExcel;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {

        String xmbhs = "37082820250001";

        String[] xmbhList = xmbhs.replace(" ", "").split("\n");
        try {
            for (String xmbh : xmbhList) {
                writeExcel(xmbh);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    static void writeExcel(String xmbh) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String sql = String.format(Sqls.sql, xmbh);
        TableMapper mapper = sqlSession.getMapper(TableMapper.class);
        List<Table> dataList = mapper.getDataList(xmbh);

        for (int i = 0; i < dataList.size(); i++) {
            dataList.get(i).set序号(i + 1);
        }

        // 填充模板
        String templateFileName = "D:\\ideaFile\\gdwp\\gdwpExcel\\src\\main\\resources\\耕地模板.xlsx";
        Calendar cal = Calendar.getInstance();
        // 目标文件名
        String fileName = String.format("附件1.耕地进出平衡“预挂钩”补充耕地%s核查表%s%s.xlsx", xmbh, (cal.get(Calendar.MONTH) + 1), cal.get(Calendar.DATE));
        // 目标文件地址
        String target = "C:\\Users\\hasee\\Desktop\\temp\\" + cal.get(Calendar.YEAR) + (cal.get(Calendar.MONTH) + 1) + cal.get(Calendar.DATE);
        File file = new File(target);
        if (!file.exists()) {
            file.mkdirs();
        }

        // 这里 会填充到第一个sheet， 然后文件流会自动关闭
        EasyExcel.write(target + "\\" + fileName).withTemplate(templateFileName).sheet().doFill(dataList);


    }
}